package com.jh.fcsm.service.sys.impl;

import com.jh.fcsm.beans.sys.SysFileInfo;
import com.jh.fcsm.dao.sys.SysFileInfoMapper;
import com.jh.fcsm.enums.FileSource;
import com.jh.fcsm.util.security.UUIDUtils;
import io.minio.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * MinIO
 *
 * @author qiubinbin
 */
@Service("minioFileServiceImpl")
public class MinioFileServiceImpl extends AbstractFileService {
    public static final Logger logger = LoggerFactory.getLogger(MinioFileServiceImpl.class);
    @Autowired
    private SysFileInfoMapper fileDao;
    @Value("${file.minio.endpoint}")
    private String endpoint;
    @Value("${file.minio.accessKey}")
    private String accessKey;
    @Value("${file.minio.secretKey}")
    private String secretKey;
    @Value("${file.minio.bucketName}")
    private String bucketName;

    public MinioClient minioClient() throws Exception {
        return MinioClient.builder()
                .endpoint(endpoint)
                .credentials(accessKey, secretKey)
                .build();
    }

    @Override
    protected SysFileInfoMapper getFileDao() {
        return fileDao;
    }



    /**
     * 文件来源
     *
     * @return
     */
    @Override
    protected FileSource fileSource() {
        return FileSource.MINIO;
    }

    /**
     * 上传文件
     *
     * @param file
     * @param fileInfo
     */
    @Override
    protected void uploadFile(MultipartFile file, SysFileInfo fileInfo) throws Exception {
//        logger.info("MinIO的uploadFile中file:{}",file);
//        logger.info("MinIO的uploadFile中fileInfo:{}",fileInfo);
        String fileName = file.getOriginalFilename();
        int index = fileInfo.getName().lastIndexOf(".");
        // 文件扩展名
        String fileSuffix = fileInfo.getName().substring(index);
        String uuidFileName = UUIDUtils.getUUID() + fileSuffix;
        try (InputStream inputStream = file.getInputStream()) {
            minioClient().putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(uuidFileName)
                            .contentType(file.getContentType())
                            .stream(inputStream, file.getSize(), -1)
                            .build());
        }
        fileInfo.setUrl(endpoint + "/" + bucketName + "/" + uuidFileName + "?attname=" + fileName);
        fileInfo.setPath(bucketName + "/" + uuidFileName);
    }

    @Override
    protected SysFileInfo uploadLocalFile(File file, SysFileInfo fileInfo) throws Exception {
        String fileName = file.getName();
        int index = fileInfo.getName().lastIndexOf(".");
        // 文件扩展名
        String fileSuffix = fileInfo.getName().substring(index);
        String uuidFileName = UUIDUtils.getUUID() + fileSuffix;

        try (InputStream inputStream = new FileInputStream(file);) {
            minioClient().putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(uuidFileName)
                            .stream(inputStream, file.length(), -1)
                            .build());
        }
        fileInfo.setUrl(endpoint + "/" + bucketName + "/" + uuidFileName + "?attname=" + fileName);
        fileInfo.setPath(bucketName + "/" + uuidFileName);
        return null;
    }


    /**
     * 上传文件
     *
     * @param file
     * @param fileInfo
     * @param markPath 指定文件目录
     */
    @Override
    protected void uploadFile(MultipartFile file, SysFileInfo fileInfo, String markPath) throws Exception {
        if (StringUtils.isNotEmpty(markPath)) {
            // 去除文件夹路径字符串的前后斜杠（/）
            markPath = StringUtils.strip(markPath, "/");
            markPath = markPath + "/";
        } else {
            markPath = "";
        }
        String fileName = file.getOriginalFilename();
        int index = fileInfo.getName().lastIndexOf(".");
        // 文件扩展名
        String fileSuffix = fileInfo.getName().substring(index);
        String uuidFileName = UUIDUtils.getUUID() + fileSuffix;
        try (InputStream inputStream = file.getInputStream()) {
            minioClient().putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(markPath + uuidFileName)
                            .contentType(file.getContentType())
                            .stream(inputStream, file.getSize(), -1)
                            .build());
        }
        fileInfo.setUrl(endpoint + "/" + bucketName + "/" + markPath + uuidFileName + "?attname=" + fileName);
        fileInfo.setPath(bucketName + "/" + markPath + uuidFileName);
    }

    /**
     * 删除文件资源
     *
     * @param fileInfo
     * @return
     */
    @Override
    protected boolean deleteFile(SysFileInfo fileInfo) {
        return false;
    }

    /**
     * 文件下载
     *
     * @param key
     * @param response
     */
    @Override
    public void down(String key, HttpServletResponse response) {

    }

    @Override
    public boolean copyFile(String source, String taraget) {
        return false;
    }
}
